package com.ruiyi.adrobot.web.controller.shop;

import com.ruiyi.adrobot.beans.Shop;
import com.ruiyi.adrobot.beans.common.ResultMsg;
import com.ruiyi.adrobot.dao.shop.ShopRepository;
import com.ruiyi.adrobot.utils.DateUtil;
import com.ruiyi.adrobot.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * Created by 51102 on 2017/6/18.
 */
@Controller
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private ShopRepository shopRepository;
    @Value("${staticPath}")
    private String staticPath;

    @GetMapping("/toList")
    public String toList() {
        return "shop/list";
    }

    @GetMapping("/toAdd")
    public String toAdd() {
        return "shop/add";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String toUpload() {
        return "product/upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam(value = "product", required = true) MultipartFile file) {
        String fileName = System.currentTimeMillis() + ".png";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 转存文件
                file.transferTo(new File("E:/pic/" + fileName));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    @GetMapping("/getListByPage")
    @ResponseBody
    public List<Shop> getListByPage() {
        return shopRepository.findAll();
    }

    @PostMapping("/add")
    @ResponseBody
    public ResultMsg add(Shop shop, @RequestParam(value = "logo", required = true) MultipartFile file) {
        shop.setCreateTime(DateUtil.getCurrentTime());
        shopRepository.save(shop);
        FileUploadUtil.FileResponse fileResponse = FileUploadUtil.uploadFile(file, staticPath + "/shops/" + shop.getId());
        shop.setLogoUrl("/shops/" + shop.getId() + "/" + fileResponse.getNewFileName());
        shopRepository.save(shop);
        return ResultMsg.success();
    }
}
